/**
 * @file CourtsService.ts
 * @description Court service for managing court data
 * @date 2024-6-4
 * @version 1.0.0
 */

import CourtsModel, { ICourt } from "../models/CourtModel";

class CourtsService {
  /** 创建球场 */
  public async createCourt(params: ICourt) {
    try {
      const court = await CourtsModel.create(params);
      return court;
    } catch (error) {
      console.error(error);
      throw error;
    }
  }

  /** 查询场馆列表 */
  public async getCourtList(params: {
    pageSize?: number;
    pageIndex?: number;
    venueId: string;
  }) {
    try {
      const { pageSize = 20, pageIndex = 1, venueId } = params;
      const filterRules: any = {};
      if (venueId) {
        filterRules.venueId = venueId;
      }
      const total = await CourtsModel.find().countDocuments();
      const list = await CourtsModel.find()
        .where(filterRules)
        .skip((pageIndex - 1) * pageSize)
        .limit(pageSize)
        .select([
          "courtId",
          "courtName",
          "courtType",
          "status",
          "capacity",
          "manager",
          "venueId",
          "comment",
          "createdAt",
          "updatedAt",
        ])
        .exec();
      return {
        total,
        pageIndex,
        pageSize,
        list,
      };
    } catch (error) {
      console.error(error);
      throw error;
    }
  }

  /** 更新球场信息 */
  public async updateCourt(params: ICourt) {
    try {
      const court = await CourtsModel.findOneAndUpdate(
        { courtId: params.courtId },
        params,
        {
          new: true,
        }
      );
      return court;
    } catch (error) {
      console.error(error);
      throw error;
    }
  }

  /** 删除球场 */
  public async deleteCourt(courtId: string) {
    try {
      const court = await CourtsModel.findOneAndDelete({ courtId });
      return court;
    } catch (error) {
      console.error(error);
      throw error;
    }
  }

  /** 获取球场信息 */
  public async getCourtById(id: string) {
    try {
      const court = await CourtsModel.findOne({ courtId: id }).select([
        "courtId",
        "courtName",
        "courtType",
        "status",
        "capacity",
        "manager",
        "venueId",
        "comment",
        "createdAt",
        "updatedAt",
      ]);
      return court;
    } catch (error) {
      console.error(error);
      throw error;
    }
  }
}

export default new CourtsService();
